<template>
  <a-layout>
    <a-layout-content>
      <a-card title="上下游碳排管理">
        <a-button type="primary" @click="showModal('add')">新增</a-button>
        <a-button @click="handleQuery" style="margin-left: 10px">查询数据</a-button>

        <a-table
          :data-source="dataSource"
          :columns="columns"
          style="margin-top: 10px"
          :pagination="pagination"
          @change="handlechange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <span class="action-buttons">
                <a @click="showModal('edit', record)" type="link">编辑</a>
                <a-divider type="vertical" />
                <a type="link" @click="handleDelete(record)">删除</a>
              </span>
            </template>
          </template>
        </a-table>
      </a-card>

      <a-modal
        v-model:open="modalVisible"
        :title="isEditMode ? '编辑外购电力热力碳排数据' : '添加外购电力热力碳排数据'"
        @ok="handleSubmit"
        @cancel="closeModal"
      >
        <a-form
          :mode="form"
          layout="horizontal"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 14 }"
        >
          <a-form-item label="供应商信息">
            <a-select
              v-model:value="addform.supplierId"
              placeholder="请选择"
              style="width: 270px"
            >
              <a-select-option
                v-for="i in Supplierdata"
                :key="i.supplierId"
                :value="i.supplierId"
              >
                {{ i.supplierName }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="碳排因子数值">
            <a-input
              v-model:value="addform.emissionFactor"
              placeholder="输入碳排因子数值"
            />
          </a-form-item>

          <a-form-item label="消耗数量">
            <a-input v-model:value="addform.quantity" placeholder="输入消耗数量" />
          </a-form-item>
          <a-form-item label="碳排放量">
            <a-input v-model:value="addform.emissionValue" placeholder="输入排放量" />
          </a-form-item>
          <a-form-item label="时间选择">
            <a-date-picker
              v-model:value="addform.timestamps"
              format="YYYY/MM/DD"
              style="width: 275px"
            />
          </a-form-item>
          <a-form-item label="活动类别">
            <a-select
              v-model:value="addform.activityCategoriesId"
              placeholder="选择活动类别"
            >
              <a-select-option
                v-for="i in activityCategories"
                :value="i.activityCategoriesId"
                >{{ i.activityCategoriesName }}</a-select-option
              >
            </a-select>
          </a-form-item>

          <a-form-item label="活动类型">
            <a-select v-model:value="addform.activityTypesId" placeholder="选择活动类型">
              <a-select-option v-for="i in activeTypes" :value="i.activityTypesId">{{
                i.activityTypesName
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="排放源名称">
            <a-select
              v-model:value="addform.sourceId"
              placeholder="选择车辆类型"
              style="width: 270px"
            >
              <a-select-option v-for="i in data" :key="i.sourceId" :value="i.sourceId">
                {{ i.sourceName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-layout-content>
  </a-layout>
</template>

<script setup>
import dayjs from "dayjs";
import { computed, onMounted, reactive, ref } from "vue";
import { selfSupportApi } from "/@/api/Carbon module/Carbon accounting module/Carbon monitoring/self-support";
import { upstream } from "/@/api/Carbon module/Carbon accounting module/Carbon monitoring/upstream";
import { supplier } from "/@/api/type/supplier";
import { smartSentry } from "/@/lib/smart-sentry";
const addform = ref({}); // 表单数据
const isEditMode = ref(false); // 标识当前是添加还是编辑模式
const Supplierdata = ref([]);
const pagination = computed(() => ({
  total: total.value,
  pageSize: queryFormState.pageSize,
  current: queryFormState.pageNum,
  showTotal: (total) => `总共${total}项`,
}));
const modalVisible = ref(false);
const dataSource = ref([]);
const tableLoading = ref(false);
const total = ref(0); //总数
const activeTypes = ref([]);
const activityCategories = ref([]);
const data = ref([]);
const queryFormState = reactive({
  pageNum: 1,
  pageSize: 10,
});
const columns = [
  {
    title: "ID",
    dataIndex: "emissionDataId",
    key: "emissionDataId",
    align: "center",
  },
  {
    title: "供应商",
    dataIndex: "supplierName",
    key: "supplierName",
    align: "center",
  },
  {
    title: "碳排因子数值",
    dataIndex: "emissionFactor",
    key: "emissionFactor",
    width: 120,
    align: "center",
  },
  {
    title: "消耗数量",
    dataIndex: "quantity",
    key: "quantity",
    width: 120,
    align: "center",
  },
  {
    title: "碳排放量",
    dataIndex: "emissionValue",
    key: "emissionValue",
    width: 120,
    align: "center",
  },
  {
    title: "时间",
    dataIndex: "timestamps",
    key: "timestamps",
    width: 170,
    align: "center",
  },
  {
    title: "活动类型",
    dataIndex: "activityCategoriesName",
    key: "activityCategoriesName",
    align: "center",
  },
  {
    title: "活动类别",
    dataIndex: "activityTypesName",
    key: "activityTypesName",
    align: "center",
  },
  {
    title: "排放源名称",
    dataIndex: "sourceName",
    key: "sourceName",
    align: "center",
  },
  {
    title: "操作",
    key: "action",
  },
  // 添加更多列...
];
const queryForm = reactive({ ...queryFormState });
async function queryData() {
  tableLoading.value = true;
  try {
    queryForm.pageNum = queryFormState.pageNum; // 确保页码同步
    queryForm.pageSize = queryFormState.pageSize;
    let queryResult = await upstream.query(queryForm);
    dataSource.value = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}
const handlechange = (pagination, filters, sorter) => {
  queryFormState.pageNum = pagination.current; // 更新当前页
  queryFormState.pageSize = pagination.pageSize; // 更新页大小
  queryData();
};
async function queryactivityTypes() {
  try {
    let queryResult = await upstream.queryactivityTypes({ pageNum: 1, pageSize: 100 });
    activeTypes.value = queryResult.data.list;
  } catch (error) {
    console.log(error);
  }
}
async function queryactivityCategories() {
  try {
    let queryResult = await upstream.queryactivityCategories({
      pageNum: 1,
      pageSize: 100,
    });
    activityCategories.value = queryResult.data.list;
  } catch (error) {
    console.log(error);
  }
}
async function Supplier() {
  try {
    let supplierresult = await supplier.query({ pageNum: 1, pageSize: 100 });
    Supplierdata.value = supplierresult.data.list;
  } catch (error) {}
}
// 请求排量类型数据
async function queryjcdata() {
  try {
    let queryResult = await selfSupportApi.queryData({ pageNum: 1, pageSize: 100 });
    data.value = queryResult.data.list;
  } catch (error) {
    console.log(error);
  }
}
const handleSubmit = async () => {
  const addresult = {
    ...addform.value,
    timestamps: dayjs(addform.value.timestamps).format("YYYY-MM-DD HH:mm:ss"),
  };
  try {
    if (isEditMode.value) {
      await upstream.update(addresult, addresult.purchasedEmissionDataId); // 编辑模式
    } else {
      await upstream.Add(addresult); // 添加模式
    }
    closeModal();
    queryData();
  } catch (error) {
    console.log(error);
  }
};
async function handleDelete(record) {
  try {
    await upstream.DElete(record.emissionDataId);
    console.log(record.emissionDataId);
    // message.success("删除成功");
    queryData();
  } catch (error) {
    console.log(error);
  }
}
const handleQuery = () => {
  console.log("查询数据");
  dataSource.value = [
    {
      id: 1,
      activityCategory: "上游活动",
      activityType: "原材料生产",
      emissionSource: "源A",
      supplierCustomer: "客户A",
    },
    // 其他数据...
  ];
};

function showModal(mode, record = null) {
  isEditMode.value = mode === "edit";
  modalVisible.value = true;

  if (isEditMode.value) {
    // 通用查找函数，根据名称查找ID
    const findIdByName = (list, name, idField, nameField) => {
      const item = list.find((item) => item[nameField] === name);
      return item ? item[idField] : null;
    };

    // 使用通用查找函数查找对应的 ID
    const activityCategoriesId = findIdByName(
      activityCategories.value,
      record.activityCategoriesName,
      "activityCategoriesId",
      "activityCategoriesName"
    );
    const activityTypesId = findIdByName(
      activeTypes.value,
      record.activityTypesName,
      "activityTypesId",
      "activityTypesName"
    );
    const supplierId = findIdByName(
      Supplierdata.value,
      record.supplierName,
      "supplierId",
      "supplierName"
    );
    const sourceId = findIdByName(
      data.value,
      record.sourceName,
      "sourceId",
      "sourceName"
    );
    addform.value = {
      ...record,
      activityCategoriesId: activityCategoriesId,
      activityTypesId: activityTypesId,
      supplierId: supplierId,
      sourceId: sourceId,
      timestamps: dayjs(record.timestamps),
    };
  } else {
    addform.value = {
      emissionDataId: "",
      supplierName: "",
      emissionFactor: "",
      quantity: "",
      emissionValue: "",
      timestamps: "",
      activityCategoriesName: "",
      activityTypesName: "",
      sourceName: "",
    };
  }
}

const closeModal = () => {
  modalVisible.value = false;
};
onMounted(() => {
  queryData();
  queryactivityTypes();
  queryactivityCategories();
  Supplier();
  queryjcdata();
});
</script>

<style scoped>
/* 添加样式 */
@import "./index.less";
</style>
